package com.blankii.androidlibrary.utils

import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * author: blankii
 * created on: 2025/4/16 14:42
 * description:
 */
object TimeUtil {
    private const val TAG = "TimeUtil"
    private var haveSetTime = false//保证应用启动一次之后只授时一次
    private var mSocketTime: Long = 0
    fun setSocketTime(isoTime: String) {
        if (!haveSetTime) {
            mSocketTime = isoToMillisLegacy(isoTime)
            haveSetTime = true
//            "授时成功====》".loge(TAG)
        }
    }

    fun getDateTimeStr(): String {
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        if (mSocketTime == 0L) {
            return sdf.format(Date())
        } else {
            mSocketTime += 1000
            return sdf.format(Date(mSocketTime))
        }

    }

    /**
     * 获取毫秒级时间戳 1752508342400
     */
    fun getTimeStamp(): String {
        if (mSocketTime == 0L) {
            return System.currentTimeMillis().toString()
        } else {
            return mSocketTime.toString()
        }
    }

    /**
     * 获取秒级时间戳
     * 1752508342
     */
    fun getTimeStamp_second(): String {
        return "${System.currentTimeMillis() / 1000}"
    }

    fun convertTime(timeStamp: Long): String {
        val seconds = timeStamp / 1000
        val date = Date(seconds * 1000L) // 注意：Date构造函数需要毫秒
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        return sdf.format(date)
    }

    fun onClear() {
        haveSetTime = false
    }

    fun isoToTimeStamp(isoString: String): String {
        // 1. 用空格替换 'T'
        val spaceReplaced = isoString.replace('T', ' ')
        // 2. 截取到秒（前 19 个字符 "yyyy-MM-dd HH:mm:ss"）
        return spaceReplaced.substring(0, 19)
    }

    fun isoToMillisLegacy(isoString: String): Long {
        val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.getDefault())
//        format.timeZone = TimeZone.getTimeZone("UTC") // 如果字符串不带时区，按需调整
        return format.parse(isoString)?.time ?: 0L
    }

}